﻿using LdtJudge.DataEngine.CallInterface;
using Microsoft.AspNetCore.Http;
using System;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Ldt.CommonCapacitySupport
{
    public class SwaggerBasicAuthMiddleware
    {
        private readonly RequestDelegate next;
        IConfigRetrieval _configRetrieval;
        public SwaggerBasicAuthMiddleware(RequestDelegate next,IConfigRetrieval configRetrieval)
        {
            _configRetrieval = configRetrieval;
            this.next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            if (context.Request.Path.StartsWithSegments("/swagger"))
            {
                string authHeader = context.Request.Headers["Authorization"];
                if (authHeader != null && authHeader.StartsWith("Basic"))
                {
                    // Get the credentials from request header
                    var header = AuthenticationHeaderValue.Parse(authHeader);
                    var inBytes = Convert.FromBase64String(header.Parameter);

                    var credentials = Encoding.UTF8.GetString(inBytes);

                    //读取配置中心CommonSetting或者CommonSettingLinux下的SwaggerUidAndPwd配置项的值进行对比验证
                    var authStr = _configRetrieval.GetAppSettingString("swaggeruidandpwd");
                    if (credentials == authStr)//authStr.Value)
                    {
                        await next.Invoke(context).ConfigureAwait(false);
                        return;
                    }
                }
                context.Response.Headers["WWW-Authenticate"] = "Basic";
                context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            }
            else
            {
                await next.Invoke(context).ConfigureAwait(false);
            }
        }
    }
}
